package com.dlc.shop.security.common.listener;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dlc.shop.bean.dto.AppConnectDTO;
import com.dlc.shop.bean.event.allinpay.AllinpayInitEvent;
import com.dlc.shop.bean.event.allinpay.CreateAllinpayMemberEvent;
import com.dlc.shop.bean.model.User;
import com.dlc.shop.security.common.model.AppConnect;
import com.dlc.shop.security.common.service.AppConnectService;
import com.dlc.shop.service.UserService;
import lombok.AllArgsConstructor;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author gaozijie
 * @date 2023-08-10
 */
@Component
@AllArgsConstructor
public class AllinpayUserInitListener {

    private final UserService userService;

    private final AppConnectService appConnectService;

    /**
     * 通联用户初始化
     * @return
     */
    @EventListener(AllinpayInitEvent.class)
    public CreateAllinpayMemberEvent allinpayUserInit(AllinpayInitEvent event) {
        CreateAllinpayMemberEvent createMemberEvent = new CreateAllinpayMemberEvent();
        // 查找用户
        List<User> users = userService.list();
        if (!CollectionUtils.isEmpty(users)) {
            List<String> userIds = users.stream().map(User::getUserId).collect(Collectors.toList());
            createMemberEvent.setUserIds(userIds);
        }
        // 查找有绑定userId的第三方用户
        List<AppConnect> appConnects = appConnectService.list(new LambdaQueryWrapper<AppConnect>()
                .isNotNull(AppConnect::getUserId));
        if (!CollectionUtils.isEmpty(appConnects)) {
            List<AppConnectDTO> appConnectDTOList = appConnects.stream().map(x -> new AppConnectDTO(x.getUserId(), x.getAppId(), x.getTempUid())).collect(Collectors.toList());
            createMemberEvent.setAppConnects(appConnectDTOList);
        }
        return createMemberEvent;
    }
}
